package model;



import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//Dao：Data Access Object  数据访问对象
//这个类创建的对象用来对blog表进行操作（增删改查）
public class BlogDao {

    //1.新增操作
    public void insert(Blog blog) throws SQLException {

      Connection connection = null;
        PreparedStatement statement = null;
        try {
            //先建立连接
          connection = DBUtil.geRelationship();
            //写SQL语句
            String sql = "insert into blog values(null, ?, ?, now(), ?)";
            //预编译
           statement = (PreparedStatement) connection.prepareStatement(sql);
            //（后端）然后就需要从服务器取数据了

            statement.setString(1, blog.getTitle()); //这里的1是指的第一个通配符号（title）
            statement.setString(2, blog.getContent()); //第二个通配符号（content）
            statement.setInt(3, blog.getUserId());    //第三个通配符
            statement.executeUpdate();
        }catch (SQLException e){
            throw new RuntimeException();
        } finally {
         DBUtil.close(connection,statement,null);
        }

    }

    //2.查询（所有的博客列表项）操作
    //这个操作是数据库中所有的blog都查询放入链表中
    public List<Blog> getBlogs() throws SQLException {

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;  //用来得到查询的结果引用
        List<Blog> blogList = new ArrayList<>();
        try{
            //建立连接
               connection = DBUtil.geRelationship();
            //写sql
            String sql = "select* from blog order by postTime desc";  //按照时间的顺序显示
            //预编译
            statement = (PreparedStatement) connection.prepareStatement(sql);
            //执行sql
            resultSet = statement.executeQuery();
            while(resultSet.next()){
                Blog blog = new Blog();
                blog.setBlogId(resultSet.getInt("blogId"));
                blog.setTitle(resultSet.getString("title"));
                //可能博客的正文太长，在博客列表页显示出来不好看所以就进行截取
                String content = resultSet.getString("content");
                if(content.length()>100){
                  content = content.substring(0,100);
                }
                blog.setContent(content);
                blog.setPostTime(resultSet.getTimestamp("postTime"));
                blog.setUseId(resultSet.getInt("userId"));
                blogList.add(blog);
            }

        }catch (SQLException e){
            throw new RuntimeException();
        }
        finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return blogList;
    }

    //3.根据博客Id查询对应的博客

    public Blog getBlog(int blogId) throws SQLException {

        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.geRelationship();
            String sql = "select* from blog where blogId=?";
            statement = (PreparedStatement) connection.prepareStatement(sql);
            statement.setInt(1,blogId);
      resultSet =  statement.executeQuery();
      if(resultSet.next()) {   //由于查询结果有1个或者没有所以用if就可以了，不需要用while了
          Blog blog = new Blog();
          blog.setBlogId(resultSet.getInt("blogId"));
          blog.setTitle(resultSet.getString("title"));
          //这个方法是希望在获取博客详情页的时候调用，所以这里正文就不需要截断了
          blog.setContent(resultSet.getString("content"));
          blog.setPostTime(resultSet.getTimestamp("postTime"));
          blog.setUseId(resultSet.getInt("userId"));
          return blog;
      }
        }catch (SQLException e){
            throw new RuntimeException();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;

    }

    //4.根据博客Id删除对应的博客
    public void deleteBlog(int blogId) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = DBUtil.geRelationship();
            String sql = "delete from blog where blogId=?";
            statement = (PreparedStatement) connection.prepareStatement(sql);
            statement.setInt(1,blogId);
            statement.executeUpdate();
        }catch (SQLException e){
            throw new RuntimeException();
        }finally {
            DBUtil.close(connection,statement,null);
        }

    }
}
